/**
 * 客户经理选择器yufp-mgr-selector
 * @param treeUrl-树的url必须
 * @param dataRoot-根节点
 * @param tabCheckbox-表格复选框
 * @param maxHeight-最大高度
 * @param roleId-角色Id
 * @param dutyId-岗位Id
 * @authors lupan
 * @date    2017-12-25 21:20:41
 * @version $1.0$
 */
(function (vue, $, name) {
  // 注册用户组件

  vue.component(name, {
    template: '<div>\
            <el-input :size="size" :icon="icon" :placeholder="placeholder" :disabled="disabled"\
            @focus="dialogVisible = true" :on-icon-click="onIconClickFn" readonly name="用户" v-model="selectedVal"></el-input>\
            <el-dialog-x title="客户经理筛选" :visible.sync= "dialogVisible" :height="height" :width = "width">\
            <el-row :gutter="20">\
            <div v-show="showtree" height="600px" width="300px">\
            <el-col :span="7">\
            <yufp-ext-tree ref="orgtree" :show-checbox="false" :check-strictly="org.checkStrictly" :default-expand-all="org.defaultExpandAll"\
            :expand-level="org.expandLevel" :root-visible="org.rootVisible" :height="org.height"\
            :data-url="org.dataUrl" :data-root="org.dataRoot" :data-id="org.dataId" :data-label="org.dataLabel" :data-pid="org.dataPid"\
            :data-params="org.dataParams" @node-click="treeClickFn" :highlightCurrent=true></yufp-ext-tree>\
            </el-col>\
            </div>\
            <el-col :span="spanShow">\
            <el-form-q ref="queryCondition" form="query"\
            :fieldData="user.fieldData" :columns="user.column" :buttons="user.buttons" :labelWidth="labelWidth"></el-form-q>\
            <el-table-x ref="usertable" :radiobox="user.checkbox" :max-height="user.maxHeight"\
            :data-url="user.dataUrl" :base-params="user.userBaseParam" :table-columns="user.tableColumns" :default-load="true"></el-table-x>\
            </el-col>\
            </el-row>\
            <div slot="footer" class="dialog-footer"  align="center">\
            <el-button @click="confirmFn">确 定</el-button>\
            <el-button @click="dialogVisible = false">取 消</el-button>\
            </div>\
            </el-dialog-x>\
            </div>',
    props: {
      value: {
        required: true
      },
      rawValue: String,
      size: String,
      disabled: {
        type: Boolean,
        default: false
      },
      placeholder: {
        type: String,
        default: '请选择'
      },
      icon: {
        type: String,
        default: 'search'
      },
      params: Object
    },
    data: function () {
      return this.createData();
    },
    created: function () {
      this.selectedVal = this.rawValue ? this.rawValue : this.value;
    },
    mounted: function () {
      this.user.userBaseParam = { condition: JSON.stringify(this.user.dataParams) };
      if (this.params != undefined) {
        if (this.params.trustFlag != undefined) {
          this.showtree = this.params.trustFlag;
          this.spanShow = 24;
        } else {
          this.showtree = true;
          this.spanShow = 19;
        }
      }
    },
    methods: {
      createData: function () {
        var me = this;
        var temp = me.getDefaultData();
        yufp.extend(true, temp, me.params);
        // if (temp.user.dataParams.roleId == '') {
        //   temp.user.fieldData.push({
        //     placeholder: '角色',
        //     field: 'roleId',
        //     type: 'select',
        //     options: []
        //   });
        //   me.setOptionsByUrl(2, backend.appOcaService + '/api/util/getrolebyuser');
        // }

        // if (temp.user.dataParams.dutyId == '') {
        //   temp.user.fieldData.push({
        //     placeholder: '岗位',
        //     field: 'dutyId',
        //     type: 'select',
        //     options: []
        //   });
        //   me.setOptionsByUrl(temp.user.fieldData.length - 1, backend.appOcaService + '/api/util/getdutybyuser');
        // }
        temp.user.dataParams.searchType = temp.org.searchType;
        return temp;
      },
      getDefaultData: function () {
        var roleLevel = '';
          for (var i = 0; i < yufp.session.roles.length; i++) {
            if (yufp.session.roles[i].checked != null) {
              roleLevel = yufp.session.roles[i].roleLevel;
            }
          }
        var me = this;
        var maxHeight;
        return {
          labelWidth: '80px',
          showtree: true,
          spanShow: 17,
          height: '500px',
          width: '1200px',
          selectedVal: '',
          dialogVisible: false,
          infoUrl: backend.appOcaService + '/api/org/getcustById',
          org: {
            rootVisible: true, // 根节点可见性
            // 设needCheckbox: false,置为默认单选
            height: 500,
            checkStrictly: false,
            defaultExpandAll: false,
            expandLevel: 2, // 默认展开层级
            dataUrl: backend.appOcaService + '/api/util/getorgtree',
            // 节点参数属性
            dataId: 'orgId',
            dataLabel: 'orgName',
            dataPid: 'upOrgId',
            dataRoot: { orgId: yufp.session.org.id, orgName: yufp.session.org.name },
            // 数据参数
            dataParams: {
              userId: yufp.session.userId,
              orgCode: yufp.session.org.code,
              needFin: false,
              needManage: false,
              needDpt: false,
              orgLevel: ''
            },
            searchType: 'CUR_ORG'
          },
          user: {
            checkbox: true,
            maxHeight: maxHeight,
            column: 4,
            fieldData: [{
              label: '员工号',
              placeholder: '员工号',
              field: 'loginCode',
              type: 'input'
            }, {
              label: '姓名',
              placeholder: '姓名',
              field: 'userName',
              type: 'input'
            }],
            buttons: [{
              label: '搜索',
              op: 'submit',
              click: function (model) {
                  me.queryFn(model);
              }
            }, {
              label: '重置',
              op: 'reset'
            }],
            dataUrl: backend.appOcaService + '/api/org/getcustmgr',
            userBaseParam: '',
            dataParams: {
              roleId: 'eaa445bdce2f42d6aa394c8a90e950ee',
              dutyId: '',
              userId: roleLevel == '4' ? yufp.session.userId: '',
              orgCode: yufp.session.org.code
            },
            tableColumns: [{
              label: '员工号',
              prop: 'orgId',
              width: '110'
            }, {
              label: '姓名',
              prop: 'orgName',
              width: '150'
            }, {
              label: '所属团队',
              prop: 'belongName',
              showOverflowTooltip: true
            }, {
              label: '所属区域',
              prop: 'areaName',
              showOverflowTooltip: true
            }
              // , {
              //   label: '所属部门编号',
              //   prop: 'dptId'
              // }, {
              //   label: '所属部门名称',
              //   prop: 'dptName'
              // }
            ]
          }
        };
      },
      setOptionsByUrl: function (order, url) {
        var me = this;
        yufp.service.request({
          url: url + '?userId=' + yufp.session.userId,
          method: 'get',
          callback: function (code, message, response) {
            if (response != null && response.data != null) {
              me.user.fieldData[order].options = response.data;
            }
          }
        });
      },
      onIconClickFn: function (val) {
        this.dialogVisible = true;
        this.$nextTick(function () {
          this.$refs.usertable.clearSelection();
        });
      },
      queryFn: function (params) {
        var roleLevel = '';
          for (var i = 0; i < yufp.session.roles.length; i++) {
            if (yufp.session.roles[i].checked != null) {
              roleLevel = yufp.session.roles[i].roleLevel;
            }
          }
        var me = this;
        var temp = params;
        // temp.dutyId = temp.dutyId == '' || temp.dutyId == undefined ? this.user.dataParams.dutyId : temp.dutyId;
        temp.orgCode = temp.orgCode == '' || temp.orgCode == undefined ? this.user.dataParams.orgCode : temp.orgCode;
        if (me.params != undefined) {
          if (me.params.trustOrg != undefined) {
            params.trustOrg = me.params.trustOrg;
          }
        }
        params.userId =  roleLevel == '4' ? yufp.session.userId: '';
        var param = { condition: JSON.stringify(params) };
        this.$refs.usertable.remoteData(param);
      },
      getCondition: function () {
        return this.$refs.queryCondition.fm;
      },
      treeClickFn: function (nodeData, node, self) {
        var params = this.getCondition();
        params.orgCode = nodeData.id;
        this.queryFn(params);
      },
      currentChangeFn: function (nodeData, node, self) {
        // 仅用于复选框
        if (this.treeCheckbox) {
          var params = this.getCondition();
          var code = this.$refs.orgtree.getCheckedKeys().toString();
          params.orgCode = code;
          this.queryFn(params);
        }
      },
      confirmFn: function () {
        var me = this;
        var data = this.$refs.usertable.selections;
        if (data.length == 0) {
          this.$message('请选择一条数据!', '提示');
          return false;
        }
        if (!this.tabCheckbox && data.length > 1) {
          this.$message('最多选择一条数据一条数据!', '提示');
          return;
        }
        this.$emit('input', this.array2String(data, 'orgId'));
        this.$emit('select-fn', data);
        this.$emit('select-fn-name', me.array2String(data, 'orgName'));
        this.$nextTick(function () {
          me.selectedVal = me.array2String(data, 'orgName');
        });
        this.dialogVisible = false;
      },
      // 对外提供选择器显示值
      getRawValue: function () {
        return this.selectedVal;
      },
      array2String: function (array, label) {
        var s = '';
        for (var i = 0; i < array.length; i++) {
          if (i == 0) {
            s += array[i][label];
          } else {
            s += ',' + array[i][label];
          }
        }
        return s;
      }
    },
    watch: {
      value: function (val) {
        var _this = this;
        this.selectedVal = '';
        yufp.service.request({
          method: 'GET',
          async: false,
          url: _this.infoUrl,
          data: {
            loginCode: val
          },
          callback: function (code, message, response) {
            if (code === 0 && response.data.length === 1) {
              _this.selectedVal = response.data[0].userName || '';
            }
          }
        });
      },
      rawValue: function (val) {
        this.selectedVal = val;
      },
      params:
      {
        handler: function (val) {
          yufp.extend(true, this, val);
          this.user.userBaseParam = { condition: JSON.stringify(this.user.dataParams) };
        },
        deep: true
      }
    }
  });
}(Vue, yufp.$, 'yufp-mgr-selector'));